import React from 'react';

export class CKHeader extends React.Component {
    constructor(props) {
        super(props);
        this.events = {};
    }

    eventHandler(key) {
        return ()=>{
            if (typeof this.events[key] === 'function') {
                this.events[key](this.props.row);
            }
        };
    }

    render() {
        return (
            <span>
                {this.renderChild()}
            </span>
        );
    }

    renderChild() {
        var value = this.props.onFormat ? this.props.onFormat(this.props.value,this.props.row):this.props.value;
        if (this.props.children) {
            return React.Children.map(this.props.children,(item,i)=>{
                if (typeof item === 'object') {
                    if (item.type === 'img') {
                        return React.cloneElement(item,{key:i,src:value});
                    } else {
                        this.events[i] = item.props.onClick || item.props.onChange;
                        return React.cloneElement(item,{key:i,onClick:this.eventHandler(i),onChange:this.eventHandler(i)});
                    }
                } else {
                    return item;
                }
            });
        } else {
            return value;
        }
    }
}

CKHeader.defaultProps = {
    text:'',
    field:'',
    value:'',
    row:null,
    onFormat:null
};

export class CKCheckbox extends React.Component {
    constructor(props) {
        super(props);
    }

    _changeHandler = ()=>{
        // this.refs.check.checked = !this.refs.check.checked;
        this.props.onChange(this.refs.check.checked);
    };

    check(flag) {
        this.refs.check.checked = flag;
        this.props.onChange(flag);
    }

    getCheck() {
        return this.refs.check.checked;
    }

    render() {
        return (<input ref="check" type="checkbox" onChange={this._changeHandler}/>);
    }
}

CKCheckbox.defaultProps = {
    onChange:function(){}
};